#!/data/data/com.termux/files/usr/bin/sh

ID=$1

if [ -z "$ID" ]; then
    echo "必须设置3位应用ID，例如: 001、012、234 等"
    echo "ID范围: 001~999，ID不能重复"
    exit 8
fi

SERVER=${IPSPOT_SERVER:="47.108.72.1"} # TODO fix me
DIST_URL=${IPSPOT_DIST_URL:="https://ipspot-dist.oss-cn-chengdu.aliyuncs.com"}

echo "DIST URL: $DIST_URL"
echo "SERVER: $SERVER"

pkg install -y openssh

mkdir bin
mkdir conf
mkdir -p .termux/boot
mkdir logs
mkdir .ssh

# download binaries
curl $DIST_URL/bin/ipspot --output bin/ipspot
curl $DIST_URL/bin/frpc --output bin/frpc
curl $DIST_URL/bin/ss-server --output bin/ss-server

# download config files
curl $DIST_URL/conf/frpc.ini --output conf/frpc.ini
curl $DIST_URL/conf/ss-server.json --output conf/ss-server.json

# donwlaod scripts
curl $DIST_URL/boot/ipspot.sh --output .termux/boot/ipspot.sh
curl $DIST_URL/boot/frpc.sh --output .termux/boot/frpc.sh
curl $DIST_URL/boot/ss-server.sh --output .termux/boot/ss-server.sh
curl $DIST_URL/boot/ssh.sh --output .termux/boot/ssh.sh

# download ssh public key
curl $DIST_URL/ssh/authorized_keys --output .ssh/authorized_keys

# set permission
chmod +x bin/ipspot
chmod +x bin/frpc
chmod +x bin/ss-server
chmod +x .termux/boot/ipspot.sh
chmod +x .termux/boot/frpc.sh
chmod +x .termux/boot/ss-server.sh
chmod +x .termux/boot/ssh.sh

# download uninstall script
curl $DIST_URL/uninstall.sh --output uninstall.sh
chmod +x uninstall.sh

# download run script
curl $DIST_URL/run.sh --output run.sh
chmod +x run.sh

# 设置配置文件
sed -i "s/{ID}/$ID/g" conf/frpc.ini
sed -i "s/{SERVER}/$SERVER/g" conf/frpc.ini
